package dao.impl;

import java.util.Iterator;
import java.util.List;

import libs.Global;
import models.User;
import dao.UserDao;

public class UserDaoImpl implements UserDao {

	@Override
	public boolean checkExistByUsername(String username) {
		return true;
	}

	@Override
	public void insert(User user) {
		Global.entityManager.getTransaction().begin();
		Global.entityManager.persist(user);
		Global.entityManager.getTransaction().commit();
	}

	@Override
	public User selectByUsernameAndPassword(String username, String password) {
		Iterator<User> iter = Global.entityManager
				.createQuery("SELECT usr FROM User AS usr WHERE usr.username = :username AND usr.password = :password",
						User.class).setParameter("username", username).setParameter("password", password)
				.getResultList().iterator();
		if (iter.hasNext()) {
			return iter.next();
		}
		return null;
	}

	@Override
	public int count(User user) {
		return Global.entityManager.createQuery("SELECT usr FROM User AS usr", Integer.class).getSingleResult();
	}

	public List<User> selectAll() {
		return Global.entityManager.createQuery("SELECT usr FROM User AS usr", User.class).getResultList();
	}

}
